package com.experian.task.job.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.experian.task.base.utils.QuartzUtil;
import com.experian.task.job.entity.QrtzCustomerJob;
import com.experian.task.job.enums.JobStatusEnum;
import com.experian.task.job.service.JobService;
import com.experian.task.job.vo.ResultVo;

@Controller
@RequestMapping("/job")
public class JobController {
	Logger logger = Logger.getLogger(JobController.class);
	@Resource(name = "jobService")
	private JobService jobService;

	@RequestMapping(value = "/jobList", method = RequestMethod.GET)
	public String jobList(HttpServletRequest request) {
		List<QrtzCustomerJob> list = jobService.findAll();
		if (list == null) {
			list = new ArrayList<QrtzCustomerJob>();
		}
		request.setAttribute("list", list);
		return "job/jobList";
	}

	/**
	 * ����ͣ�ö�ʱ����
	 * @param status
	 * @param name
	 * @param gname
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	@ResponseBody
	public ResultVo eidt(String status, String name, String gname) {
		ResultVo vo = new ResultVo();
		try {
			QrtzCustomerJob job = new QrtzCustomerJob();
			job.setName(name);
			job.setGname(gname);
			job = jobService.findByNameAndGname(job);
			QuartzUtil quartzUtil = new QuartzUtil();
			//���������
			if (JobStatusEnum.RUNNING.getStatus().equals(status)) {
				quartzUtil.removeJob(job.getName(), job.getGname());
				quartzUtil.addJob(job.getName(), job.getGname(), (Class<Job>) Class.forName(job.getJob()), job.getCron());
				job.setStatus(JobStatusEnum.RUNNING.getStatus());
				jobService.update(job);
			} 
			//�����ͣ��
			else if (JobStatusEnum.STOP.getStatus().equals(status)) {
				quartzUtil.removeJob(name, gname);
				job.setStatus(JobStatusEnum.STOP.getStatus());
				jobService.update(job);
			}
			vo.setCode(ResultVo.SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			vo.setCode(ResultVo.FALSE);
		}
		return vo;
	}
}
